#include "Server.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iostream>
#include <string.h>
#include <string>
#include "../Stringops/StringOps.h"
#include <stdlib.h>

using namespace std;

#define TFTPPORT 69;
int buildServer(int argc, char*argv[]);

bool ipcheck(std::string _host) {
        std::vector<std::string> parts = split(_host, '.');
        for(unsigned int i = 0; i < parts.size(); i++)
                if(!is_numeric(parts[i]))
                        return false;
        return true;
}

int main(int argc, char*argv[]){
	int mainRtn = 0;
	mainRtn = buildServer(argc, argv);
	if(mainRtn < 0) {
		exit(1);
	}
	return mainRtn;	
}

int buildServer(int argc, char*argv[]){
	char* _host;
	string _port;
	string _server_dir = "./";
	if(argc!=3){
		printf("correct command:<server> <server ip> <port number>\n");
		return 1;
	}else{
		_host = argv[1];
		_port = argv[2];
		if(ipcheck(_host) && is_numeric(_port)){
			Server TFTPServ(_host, atoi(_port.c_str()), _server_dir);
			TFTPServ.retry_limit = RETRY_LIMIT;
			TFTPServ.first_interval = FIRST_INTERVAL;
			if(TFTPServ.incoming_sock == 0) {
				// Couldn't bind to port
				return -1;
			}
			TFTPServ.handle_server_connection();
			TFTPServ.stop_server();
		}else{
			printf("server's ip address is not correct!\n");
			return 1;
		}
			
	}	
	return 0;
}
